#coding=utf8
from google.appengine.ext import db

# http log save

class GuestIP(db.Model):
    "ipaddress of vister"
    ipaddr = db.StringProperty(required=True)
    viewcnt = db.IntegerProperty(required=True)
    # latest visit datetime
    visit_time = db.IntegerProperty(required=True)
    
class RequestReferer(db.Model):
    "where "
    
def get_all_guest_ip():
    return db.GqlQuery("SELECT * FROM GuestIP").fetch(1000)

def get_specify_ip(ipaddr):
    if not ipaddr:
        return None
    return db.GqlQuery("SELECT * FROM GuestIP WHERE ipaddr=:1", ipaddr).get()

def put_guest_ip(ipaddr):
    from time import time
    if not ipaddr:
        return None
    if type(ipaddr) != type(''):
        return None
    gip = get_specify_ip(ipaddr)
    if gip:
        gip.viewcnt += 1
        gip.visit_time = int(time())
        return gip.put()
    else:
        gip = GuestIP(ipaddr = ipaddr,
                      visit_time = int(time()),
                      viewcnt = 1)
        return gip.put()

def delete_specify_ip(ipaddr):
    gip = get_specify_ip(ipaddr)
    if gip:
        gip.delete()
        return True
    return False

def clean_all_ip():
    iplist = get_all_guest_ip()
    if not iplist:
        return
    for ip in iplist:
        ip.delete()
    return

def write_guest_log(request):
    "guest log module"
    # this function will be call every http request
    # so it must be fast
    put_guest_ip(request.remote_addr)
    # parse and save the referer
    # print request.referer
